package com.lujianfei.powersearch.ui.subitem

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.base.BaseActivity
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.databinding.ActivitySubItemBinding
import com.lujianfei.powersearch.timer.GlobalTimerManager
import com.lujianfei.powersearch.ui.createOrUpdate.CreateOrUpdateActivity
import com.lujianfei.powersearch.ui.report.TotalConsumeReportActivity
import com.lujianfei.powersearch.ui.search.SearchActivity
import com.lujianfei.powersearch.ui.select.SelectNodeActivity
import com.lujianfei.powersearch.ui.sort.SortItemActivity
import com.lujianfei.powersearch.ui.subitem.ActivityStackManager.Companion.instance
import com.lujianfei.powersearch.ui.subitem.ActivityStackManager.StackInfo
import com.lujianfei.powersearch.ui.subitem.viewmodel.SubItemViewModel
import com.lujianfei.powersearch.utils.AppJumpUtils
import com.lujianfei.powersearch.utils.SystemUtils
import com.lujianfei.powersearch.utils.ToastUtils

class SubItemActivity : BaseActivity<ActivitySubItemBinding>(), GlobalTimerManager.OnGlobalCallback {

    companion object {

        const val REQUEST_CODE_SELECT_NODE = 100
        fun jumpSubItemActivity(context: Context, item: SearchItemModel?) {
            val intent = Intent(context, SubItemActivity::class.java)
            intent.putExtra("data", item)
            context.startActivity(intent)
        }
    }
    private var stackInfo: StackInfo? = null
    private val mSubItemViewModel: SubItemViewModel by lazy { buildViewModel() }

    override fun resourceId() = R.layout.activity_sub_item

    override fun initView() {
        binding?.vm = mSubItemViewModel
        GlobalTimerManager.instance.addObserver(observer = this)
        binding?.breadCrumbs?.parentId = mSubItemViewModel.searchItemModel?.id?:0
    }

    override fun initData() {
        parseIntent()
    }

    override fun initEvent() {
        mSubItemViewModel.onItemClickCallback = { item ->
            jumpSubItemActivity(this@SubItemActivity,item)
        }
        mSubItemViewModel.onItemLongClickCallback = { model ->
            val items = arrayOf("复制", "编辑", "生成报表", "移动", "取消")
            AlertDialog.Builder(this@SubItemActivity).setTitle("提示").setItems(items) { dialog, which ->
                dialog.dismiss()
                val item = items[which]
                if ("复制".equals(item, ignoreCase = true)) {
                    SystemUtils.copy(model.name)
                } else if ("编辑".equals(item, ignoreCase = true)) {
                    CreateOrUpdateActivity.jumpCreateOrUpdateActivity(this, model)
                } else if ("移动".equals(item, ignoreCase = true)) {
                    mSubItemViewModel?.searchItemModelFromLongClick = model
                    SelectNodeActivity.start(this,searchItemModel = null, selectId = model.id, requestCode = REQUEST_CODE_SELECT_NODE)
                } else if ("生成报表".equals(item, ignoreCase = true)) {
                    TotalConsumeReportActivity.start(this, model)
                }
            }.show()
            true
        }
        binding?.searchBar?.setOnClickListener { SearchActivity.jumpSearchActivity(this@SubItemActivity,
            mSubItemViewModel.searchItemModel?.id?:0) }
    }


    private fun parseIntent() {
        mSubItemViewModel.searchItemModel = intent.getParcelableExtra("data")
        stackInfo = StackInfo(mSubItemViewModel.searchItemModel, this as BaseActivity<ViewDataBinding>)
        instance.push(stackInfo!!)
        setTitleMiddleText(mSubItemViewModel.searchItemModel?.name)
    }

    override val titleBarResId = R.id.toolbar
    override val menuResId: Int = R.menu.sub_item_menu

    override fun handleRightButton(itemId: Int) {
        super.handleRightButton(itemId)
        when (itemId) {
            R.id.action_add -> CreateOrUpdateActivity.jumpCreateActivity(this,
                mSubItemViewModel.searchItemModel
            )
            R.id.action_sort -> SortItemActivity.jumpSortItemActivity(this,
                mSubItemViewModel.searchItemModel
            )
            R.id.action_parent -> jumpSubItemActivity(this,
                mSubItemViewModel.getParent()
            )
        }
    }

    override fun onResume() {
        super.onResume()
        mSubItemViewModel.loadData()
    }

    override fun onDestroy() {
        instance.remove(stackInfo!!)
        GlobalTimerManager.instance.removeObserver(observer = this)
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            REQUEST_CODE_SELECT_NODE-> {
                val searchItemModel:SearchItemModel? = data?.getParcelableExtra("data")
                searchItemModel?.let {
                    mSubItemViewModel.moveTo(it)
                    ToastUtils.show("已移动至\"${it.name}\"")
                }
            }
        }
    }

    override fun onGlobalTimerCallback() {
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            mSubItemViewModel.updateCountDown()
        }
    }
}